package com.atguigu.auth.service.Impl;

import com.atguigu.auth.mapper.SysMenuMapper;
import com.atguigu.auth.mapper.SysUserRoleMapper;
import com.atguigu.auth.service.SysMenuService;
import com.atguigu.common.execption.GuiguException;
import com.atguigu.model.system.SysMenu;
import com.atguigu.model.system.SysRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 12646
 * @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
 * @createDate 2023-11-15 14:45:31
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService {
  @Autowired
  private SysMenuMapper sysMenuMapper;
  @Autowired
  private SysUserRoleMapper sysUserRoleMapper;
  
  @Override
  public boolean removeById(Serializable id) {
    // 例如要删除用户管理，id为3，ParentId里面也有3，所以不能删除
    int count = this.count(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentId, id));
    if (count > 0) {
      throw new GuiguException(201, "请先删除所有子菜单");
    }
    sysMenuMapper.deleteById(id);
    return false;
  }
  
  @Override
  public List<SysMenu> findUserMenuList(Long userId) {
    // 1. 判断当前用户是否是管理员  （这个项目中userId为1就是管理员）
    // 如果是管理员，查询所有菜单
    if (userId == 1) {
      QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
      return sysMenuMapper.selectList(wrapper);
    } else {
      // 如果不是管理员，查询对应菜单
      List<SysRole> sysRoleList = sysUserRoleMapper.selectRoleByUserId(userId); // 获取用户对应的角色列表
      for (SysRole role : sysRoleList) {
        return sysMenuMapper.selectUserMenu(role.getId());
      }
    }
    return null;
  }
  
  @Override
  public List<String> findUserPermsByUserId(Long userId) {
    //超级管理员admin账号id为：1
    List<SysMenu> sysMenuList = null;
    if (userId == 1) {
      sysMenuList = this.list(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getStatus, 1));
    } else {
      List<SysRole> sysRoleList = sysUserRoleMapper.selectRoleByUserId(userId); // 获取用户对应的角色列表
      for (SysRole role : sysRoleList) {
        sysMenuList =  sysMenuMapper.selectUserMenu(role.getId());
      }
    }
    // 菜单表里面type为2就是按钮
    List<String> permsList = sysMenuList.stream().filter(item -> item.getType() == 2).map(item -> item.getPerms()).collect(Collectors.toList());
    return permsList;
  }
  
  
 
}




